package org.jeecg.modules.xl.store.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.AddressResolution;
import com.kuaidi100.sdk.core.IBaseClient;
import com.kuaidi100.sdk.pojo.HttpResult;
import com.kuaidi100.sdk.request.AddressResolutionReq;
import com.kuaidi100.sdk.request.addressResolution.AddressResolutionParam;
import com.kuaidi100.sdk.response.addressResolution.AddressResolutionResp;
import com.kuaidi100.sdk.utils.SignUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.xl.cityconfig.entity.XlConfigCityDelivery;
import org.jeecg.modules.xl.cityconfig.service.IXlConfigCityDeliveryService;
import org.jeecg.modules.xl.store.entity.XlCustomerMystore;
import org.jeecg.modules.xl.store.entity.XlCustomerStoreInfo;
import org.jeecg.modules.xl.store.mapper.XlCustomerMystoreMapper;
import org.jeecg.modules.xl.store.mapper.XlCustomerStoreInfoMapper;
import org.jeecg.modules.xl.store.service.IXlCustomerStoreInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Description: 客户门店信息
 * @Author: jeecg-boot
 * @Date:   2024-10-24
 * @Version: V1.0
 */
@Service
public class XlCustomerStoreInfoServiceImpl extends ServiceImpl<XlCustomerStoreInfoMapper, XlCustomerStoreInfo> implements IXlCustomerStoreInfoService {

	@Autowired
	private ISysDepartService sysDepartService;
	@Autowired
	private XlCustomerStoreInfoMapper xlCustomerStoreInfoMapper;
	@Autowired
	private XlCustomerMystoreMapper xlCustomerMystoreMapper;

   @Autowired
   private IXlConfigCityDeliveryService xlConfigCityDeliveryService;
	@Override
	public List<XlCustomerStoreInfo> selectStoresByLoginUserId(LoginUser loginUser) {
		//当前用户的角色
		String roles = loginUser.getRoleCode();

		boolean isAdmin =false;
		String [] s = {"slt_admin","admin"};
		if(StrUtil.containsAny(roles,s)){
			isAdmin = true;
		}
		//当前用户的组织机构（客户），如果有绑定门店，有从这里获取
		List<SysDepart> departs =  sysDepartService.queryUserDeparts(loginUser.getId());
		//根据逻辑来说，每个登录账号只允许挂一个组织，如果有多个
		String departNames ="";
		if(ObjectUtil.isNotEmpty(departs)){
			departNames = departs.stream()
					//.map(SysDepart::getDepartName) // 提取 code 字段
					.map(sysDepart -> "'" + sysDepart.getDepartName() +"'")
					.collect(Collectors.joining(",")); // 以逗号拼接

		}
		//如果是管理员，就返回全部的门店数据
		if(isAdmin){
			return this.list();
		}
		// 否则，就返回登录用户所在的组织（也就是客户）下的所有门店
		return this.selectStoresInDepartName(departNames);
	}

	@Override
	@Cacheable(cacheNames = "storeInfo#3600",key = "#storeCode")
	public XlCustomerStoreInfo getStoreInfoCacheable(String storeCode) {
		QueryWrapper<XlCustomerStoreInfo> storeInfoQueryWrapper = new QueryWrapper<>();
		storeInfoQueryWrapper.eq("store_code",storeCode);
		return baseMapper.selectOne(storeInfoQueryWrapper);
	}

	@Override
	public List<XlCustomerStoreInfo> selectStoresInDepartName(String departnames) {
		return baseMapper.selectStoresInDepartName(departnames);
	}
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(XlCustomerStoreInfo xlCustomerStoreInfo, List<XlCustomerMystore> xlCustomerMystoreList) {
		//生成门店编号 渠道编号+5位流水号
		int maxNumber = getStringNumber(baseMapper.queryMaxCodeNumber(xlCustomerStoreInfo.getCustomerTypeCode()));
		xlCustomerStoreInfo.setStoreCode(xlCustomerStoreInfo.getCustomerTypeCode() + String.format("%05d", maxNumber+1));
		xlCustomerStoreInfo.setStoreLevel("三批");
		xlCustomerStoreInfo.setStoreType("加盟");

        try {
//            AddressResolutionResp resolutionResp = addressResolution(xlCustomerStoreInfo.getStoreAddress());
//			//调用快递100的智能地址解析接口获取省市区，并复制
//			 xlCustomerStoreInfo.setProvince(resolutionResp.getResult().get(0).getXzq().getProvince()+"省");
//			 xlCustomerStoreInfo.setCity(resolutionResp.getResult().get(0).getXzq().getCity());
//			 xlCustomerStoreInfo.setDistrict(resolutionResp.getResult().get(0).getXzq().getDistrict());
			 //如果门店所在城市是属于城配城市，则运输类型为城配，否则为一键代发
			Map<String, XlConfigCityDelivery>  xlConfigCityDeliveryMap = xlConfigCityDeliveryService.getXlConfigCityDeliveryMapList();//getOne(new QueryWrapper<XlConfigCityDelivery>().eq("city",xlCustomerStoreInfo.getCity()));
			if(xlConfigCityDeliveryMap.containsKey(xlCustomerStoreInfo.getCity())){
				xlCustomerStoreInfo.setDeliveryWay("1");//所在城市为城配城市
			}else{
				xlCustomerStoreInfo.setDeliveryWay("2");//所在城市为一键代码城市
			}
			xlCustomerStoreInfoMapper.insert(xlCustomerStoreInfo);
			if(xlCustomerMystoreList!=null && xlCustomerMystoreList.size()>0) {
				for(XlCustomerMystore entity:xlCustomerMystoreList) {
					//外键设置
					entity.setId(null);
					entity.setStoreCode(xlCustomerStoreInfo.getStoreCode());
					entity.setStoreName(xlCustomerStoreInfo.getStoreName());
					entity.setStoreLevel(xlCustomerStoreInfo.getStoreLevel());
					xlCustomerMystoreMapper.insert(entity);
				}
			}
        } catch (Exception e) {
            throw new RuntimeException(e);
        }



	}

	/**
	 * 获取字符中的数字
	 * @param str
	 * @return
	 */
	private int getStringNumber(String str){
		if (str == null){
			return 0;
		}
		StringBuilder numbers = new StringBuilder();

		// 定义正则表达式，匹配数字
		Pattern pattern = Pattern.compile("\\d+");
		Matcher matcher = pattern.matcher(str);

		// 查找所有匹配的数字
		while (matcher.find()) {
			numbers.append(matcher.group()); // 添加到结果中
		}
		return Integer.parseInt(numbers.toString());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(XlCustomerStoreInfo xlCustomerStoreInfo,List<XlCustomerMystore> xlCustomerMystoreList) {
		xlCustomerStoreInfoMapper.updateById(xlCustomerStoreInfo);
		
		//1.先删除子表数据
		xlCustomerMystoreMapper.deleteByMainId(xlCustomerStoreInfo.getId());
		
		//2.子表数据重新插入
		if(xlCustomerMystoreList!=null && xlCustomerMystoreList.size()>0) {
			for(XlCustomerMystore entity:xlCustomerMystoreList) {
				//外键设置
				entity.setId(null);
				entity.setStoreCode(xlCustomerStoreInfo.getStoreCode());
				entity.setStoreName(xlCustomerStoreInfo.getStoreName());
				entity.setStoreLevel(xlCustomerStoreInfo.getStoreLevel());
				xlCustomerMystoreMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		xlCustomerMystoreMapper.deleteByMainId(id);
		xlCustomerStoreInfoMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			xlCustomerMystoreMapper.deleteByMainId(id.toString());
			xlCustomerStoreInfoMapper.deleteById(id);
		}
	}

	private AddressResolutionResp addressResolution(String address) throws Exception {
		 String key = "apCDGXjp8152";
		 String customer = "3E163C1F545E1D6C38EC8DABE13293B3";
		 String secret ="c28bd653d6bc405288bb31ffe799e741";
		 String userid =  "c28bd653d6bc405288bb31ffe799e741";

		AddressResolutionParam addressResolutionParam = new AddressResolutionParam();
		//content 、image、imageUrl、pdfUrl、htmlUrl必填其一，优先顺序：content >image>imageUrl>padUrl>htmlUrl
		addressResolutionParam.setContent(address);
		//image传base64编码
		// addressResolutionParam.setImage("");
		// addressResolutionParam.setImageUrl("http://api.kuaidi100.com/label/getImage/20240621/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
		// addressResolutionParam.setPdfUrl("http://api.kuaidi100.com/label/xxx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
		// addressResolutionParam.setHtmlUrl("http://api.kuaidi100.com/label/xxx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
		String param = new Gson().toJson(addressResolutionParam);
		String t = System.currentTimeMillis() + "";
		AddressResolutionReq addressResolutionReq = new AddressResolutionReq();
		addressResolutionReq.setT(t);
		addressResolutionReq.setKey(key);
		addressResolutionReq.setSign(SignUtils.printSign(param,t,key,secret));
		addressResolutionReq.setParam(param);
		IBaseClient baseClient = new AddressResolution();
		//System.out.println(baseClient.execute(addressResolutionReq));
		HttpResult result = baseClient.execute(addressResolutionReq);
		// System.out.println(result);
		JSON json = JSONUtil.parse(result.getBody());
		AddressResolutionResp addressResolutionResp = new Gson().fromJson(json.getByPath("data").toString(), AddressResolutionResp.class);
		return  addressResolutionResp;
	}


}
